package com.hcy.app.api

import android.util.Log
import com.hcy.app.data.GlobalState
import com.hcy.app.data.dao.SettingsRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import okhttp3.Interceptor
import okhttp3.Response
import javax.inject.Inject

class InterceptorForTokenRefresh: Interceptor {

    @Inject lateinit var settingsRepo: SettingsRepository

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)

        // 直接使用缓存的 token
        request.newBuilder()
            .header("Authorization", GlobalState.CapToken)
            .build()

        if ( GlobalState.CapTokenExpires - System.currentTimeMillis() < 5*60 ){
//            synchronized(this) {
//                val resDto = RetrofitManage.apiService.refreshToken().result
//                Log.d(TAG, resDto.toString())
//                resDto?.expires?.let {
//                    CoroutineScope(Dispatchers.IO).launch {
//                        GlobalState.CapToken = resDto.token
//                        GlobalState.CapTokenExpires = resDto.expires.toLong()
//                        settingsRepo.saveCapToken(resDto.token,resDto.expires.toLong())
//                    }
//                    return chain.proceed(request.newBuilder()
//                        .build())
//                }
//            }
        }
//        return chain.proceed(request.newBuilder().build())
        return response
    }
    companion object {
        private const val TAG = "TokenRefreshInterceptor"
    }
}